﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Gasco.Business.Services;
using Gasco.DataAccess;
using Mani.Common;
using Gasco.Business.Workflows;

public partial class Controls_order_index : System.Web.UI.UserControl
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!Page.IsPostBack)
        {
            LoadOrders(1, true, gvOrder.SortExpression, gvOrder.SortDirection.ToString());
        }
    }

    private void LoadOrders(int pageNumber, bool setPageCount, string sortBy, string sortDirection)
    {
        ViewState["CurrentPage"] = pageNumber;

        IOrderService os = new OrderService();
        if (setPageCount)
            gvOrder.VirtualItemCount = os.CountGetOrders();

        if (Request.QueryString["purchase"] != null)
        {
            tbSearch.Text = Request.QueryString["purchase"];
            tbSearch.Visible = false;
            lbSearch.Visible = false;
            tbNewOrder.Visible = false;
            lbtitle.Visible = false;
            gvTitle.Visible = false;
        }

        int orderType = 1;
        if (Request.QueryString["order_type"] != null)
        {
            orderType = Convert.ToInt32(Request.QueryString["order_type"]);
        }

        gvOrder.DataSource = os.GetOrders(tbSearch.Text, orderType, gvOrder.PageSize, pageNumber, sortBy, sortDirection);
        gvOrder.DataBind();
    }

    protected void gvOrder_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvOrder.PageIndex = e.NewPageIndex;
        LoadOrders(e.NewPageIndex + 1, false, gvOrder.SortExpression, gvOrder.SortDirection.ToString());
    }

    protected void gvOrder_Deleting(object sender, GridViewDeleteEventArgs e)
    {
        OrderService os = new OrderService();
        try
        {
            os.DeleteOrder(Convert.ToInt32(gvOrder.DataKeys[e.RowIndex].Value));
            LoadOrders(1, true, gvOrder.SortExpression, gvOrder.SortDirection.ToString());
        }
        catch (OrderHasSaleOrdersException)
        {
            UIHelper.ClientAlert(this.Page, GetLocalResourceObject("OrderHasSaleOrdersException").ToString());
        }
    }

    protected void gvOrder_Sorting(object sender, GridViewSortEventArgs e)
    {

        if (ViewState["sort"] == null || ViewState["sort"].ToString() == "asc")
        {
            e.SortDirection = SortDirection.Descending;
            ViewState["sort"] = "desc";
        }
        else
        {
            e.SortDirection = SortDirection.Ascending;
            ViewState["sort"] = "asc";
        }

        LoadOrders(gvOrder.PageIndex + 1, false, e.SortExpression, e.SortDirection.ToString());
    }

    protected void gvOrder_RowDataBound(object sender, GridViewRowEventArgs e)
    {
        if (e.Row.RowType == DataControlRowType.DataRow)
        {
            order o = (order)e.Row.DataItem;
            OrderStates state = (OrderStates)o.order_status_id;

            IOrderWorkflow orderWorkflow = WorkflowFactory.LoadOrderWorkflow(o);
            Dictionary<int, Transition> transitions = orderWorkflow.GetTransitionsByState(o.order_status_id);

            int i = 1;
            foreach (KeyValuePair<int, Transition> t in transitions)
            {
                LinkButton linkButton = (LinkButton)e.Row.FindControl("LinkButton" + i.ToString());
                setLinkButtonEvent(linkButton, GetLocalResourceObject(t.Value.Name).ToString(), (OrderEvent)t.Key, o.id);
                i++;
            }

            if (o.order_status_id == (int)OrderStates.WaitingForPriceCalc)
            {
                LinkButton linkButton = (LinkButton)e.Row.FindControl("LinkButton" + i.ToString());
                setLinkButtonRedirect(linkButton, GetLocalResourceObject("CalculatePriceLink").ToString(), "loader.aspx?calculate_price", o.id);
            }
        }
    }

    private void setLinkButtonEvent(LinkButton link, string text, OrderEvent ev, int orderId)
    {
        link.Text = text;
        link.CommandName = "EV" + ((int)ev).ToString();
        link.Visible = true;
        link.CommandArgument = orderId.ToString();
    }

    private void setLinkButtonRedirect(LinkButton lnk, string text, string url, int oid)
    {
        lnk.Text = text;
        lnk.PostBackUrl = url + "&orderid=" + oid;
        lnk.Attributes["href"] = url + "&orderid=" + oid;
        lnk.CssClass = "popup";
        lnk.Visible = true;
    }

    protected void gvOrder_RowCommand(object sender, GridViewCommandEventArgs e)
    {
        if (e.CommandName.Substring(0, 2) == "EV")
        {
            LinkButton link = (LinkButton)e.CommandSource;
            OrderService os = new OrderService();
            order o = os.GetOrderById(int.Parse(link.CommandArgument));
            IOrderWorkflow orderWorkflow = WorkflowFactory.LoadOrderWorkflow(o);

            OrderEvent eventid = (OrderEvent)int.Parse(link.CommandName.Substring(2));

            try
            {
                orderWorkflow.SendEvent(eventid);
            }
            catch (TransitionException tx)
            {
                if (tx.Failure == TransitionException.Type.GuardFailed)
                {
                    string alert = GetLocalResourceObject(tx.Error).ToString();
                    UIHelper.ClientAlert(this.Page, alert);
                }
                else throw;
            }

            LoadOrders(gvOrder.PageIndex + 1, false, gvOrder.SortExpression, gvOrder.SortDirection.ToString());
        }
    }

    protected void lbSearch_Click(object sender, EventArgs e)
    {
        LoadOrders(1, true, gvOrder.SortExpression, gvOrder.SortDirection.ToString());
    }
}
